package org.piwicode.bywordofmouth;

import com.googlecode.cqengine.attribute.SimpleAttribute;
import java.io.File;
import java.io.Serializable;
import java.nio.file.Path;
import java.text.Normalizer;
import java.util.Objects;

/**
 *
 * @author pierre
 */
public class FileResource implements Serializable, Resource {

    private final Resource parent;
    private final String name;
    private final long lastModified;
    private final long length;

    public FileResource(Resource parent, String name, long lastModified, long length) {
        this.parent = parent;
        this.name = name;
        this.lastModified = lastModified;
        this.length = length;
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public String toString() {
        return parent == null ? name : parent.toString() + "/" + name;
    }

    @Override
    public long lastModified() {
        return lastModified;
    }

    @Override
    public long length() {
        return length;
    }

    @Override
    public Path path() {
        return parent.path().resolve(name);
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 37 * hash + Objects.hashCode(this.name);
        hash = 37 * hash + (int) (this.lastModified ^ (this.lastModified >>> 32));
        hash = 37 * hash + (int) (this.length ^ (this.length >>> 32));
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final FileResource other = (FileResource) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        if (this.lastModified != other.lastModified) {
            return false;
        }
        if (this.length != other.length) {
            return false;
        }
        return true;
    }
    public static final SimpleAttribute<Resource, String> NAME =
            new SimpleAttribute<Resource, String>("resourceName") {
        @Override
        public String getValue(Resource o) {
            return normalize(o.name());
        }
    };
    public static final SimpleAttribute<Resource, Resource> PARENT =
            new SimpleAttribute<Resource, Resource>("parent") {
        @Override
        public Resource getValue(Resource o) {
            return o.parent();
        }
    };

    public static String normalize(final String txt) {
        return Normalizer.normalize(txt, Normalizer.Form.NFD)
                .replaceAll("\\p{InCombiningDiacriticalMarks}|\\s", "")
                .toLowerCase();
    }

    @Override
    public boolean isDirectory() {
        return length == -1;
    }

    @Override
    public Resource parent() {
        return parent;
    }
}
